package com.icebergteam.warfacewidget.rank.data;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Date;

import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.icebergteam.warfacewidget.AppManager;
import com.icebergteam.warfacewidget.WidgetProvider;
import com.icebergteam.warfacewidget.core.LogManager;
import com.icebergteam.warfacewidget.core.Parser;
import com.icebergteam.warfacewidget.core.ParserException;
import com.icebergteam.warfacewidget.core.connection.NetworkManager;
import com.icebergteam.warfacewidget.core.utils.ViewUtils;
import com.icebergteam.warfacewidget.data.sql.RankTable;
import android.content.ContentValues;
import android.database.SQLException;

public class Top100Parser extends Parser  {
	final public static String className = Top100Parser.class.getCanonicalName();
	
	
	public Top100Parser(boolean restoreKey) {
		super(restoreKey);
	}

	public Top100Parser() {
		super();
	}
	@Override
	public int saveData(String url) throws Exception, ParserException, SQLException {
		try {
			if (this.isRestoreKey() && AppManager.getDatabase().getRankTable().getCountCurrentUrl()>0){
				LogManager.LogV(Top100Parser.className, LogManager.getExecuteMethodName(),
						"generate restore");
				throw new Exception(WidgetProvider.RESTORE_ACTION); 
			}
			LogManager.LogVA(Top100Parser.className, url);
			this.setRestoreKey(false);
			this.doc = Jsoup.parse(NetworkManager.getResponseInputStream(url), "UTF-8", "");
			
			ContentValues dataToInsert = new ContentValues();    
			dataToInsert.put(RankTable.FIELD_URL, url);
			dataToInsert.put(RankTable.FIELD_HTML, this.doc.toString());
			dataToInsert.put(RankTable.FIELD_PUBDATE, new Date().getTime());
			
						
			AppManager.getDatabase().getRankTable().updateOrInsert(dataToInsert);

			this.stateRequest = Top100Parser.REQUEST_COMPLETED;
			LogManager.LogV(Top100Parser.className,  LogManager.getExecuteMethodName(), url);

		} catch (SocketTimeoutException e) {
			restore(Parser.REQUEST_FAILED | Parser.LIST_RESTORED,
										Parser.REQUEST_FAILED | Top100Parser.LIST_RESTORED);
			throw new ParserException(ViewUtils.getErrorMessage(e), this.stateRequest);
		} catch (IOException e) {
			restore(Parser.REQUEST_FAILED | Parser.LIST_RESTORED,
								Top100Parser.REQUEST_FAILED);
			throw new ParserException(ViewUtils.getErrorMessage(e), this.stateRequest);
		}catch (SQLException e) {
			this.stateRequest = Parser.DB_INVALID;
			throw new ParserException(ViewUtils.getErrorMessage(e), this.stateRequest);
			
		}catch (Exception e) {
			if (WidgetProvider.RESTORE_ACTION.equals(e.getMessage())) {
				restore(Parser.LIST_RESTORED, Parser.REQUEST_FAILED);
			}
			else{
				this.stateRequest = (Parser.REQUEST_FAILED);
			}
			
			throw new ParserException(ViewUtils.getErrorMessage(e), this.stateRequest);
		}
		return this.stateRequest;
	}
	@Override
	protected void restore(int complete, int failed)	throws Exception {
		try {
			int count = AppManager.getDatabase().getRankTable().getCountCurrentUrl();
			
			if(count == -1){
				throw new Exception( LogManager.getExecuteMethodName() + " - DB empty");
			}
			this.stateRequest = complete;
			LogManager.LogV(Top100Parser.className,  LogManager.getExecuteMethodName());
		}catch (SQLException e) {
			throw new SQLException(String.format(
					"%s - error = %s",  LogManager.getExecuteMethodName(), ViewUtils.getErrorMessage(e)));
		}catch (Exception e1) {
			this.stateRequest = failed;
			throw new Exception(String.format(
					"%s - error = %s",  LogManager.getExecuteMethodName(),ViewUtils.getErrorMessage(e1)));
		}
	}
	
	@Override
	public ArrayList<Top100Item> parseXML(Document doc, int limit) throws Exception {
		try {
			LogManager.LogEA(className,  doc.select("li").size());
			ArrayList<Top100Item> top100List = new ArrayList<Top100Item>();
			
			Elements listPlayers = doc.select("li");
			
			int index = 0;
			for (Element listElement: listPlayers) {
				top100List.add(this.getItem(listElement));
				index++;

				if(limit >= 0 && index == limit) break;
			}
			
			return top100List;
		} 
		catch (Exception e) {
			this.stateRequest = Top100Parser.XML_INVALID;

			throw new ParserException(String.format(
					"%s - doc = %s; error = %s",  LogManager.getExecuteMethodName(), (doc == null) ? doc == null :"yes", ViewUtils.getErrorMessage(e)), this.stateRequest);
		}
	}
	
	@Override
	protected Top100Item getItem(Element elem) throws Exception{
		Top100Item item = new Top100Item();
		item.setPos(this.parseInt(elem.select("div.position").first().text()));
		item.setNickname(elem.select("div.nickname").first().text());
		item.setProgress(this.parseInt(elem.select("div.progress").first().attr("style")));
		item.setClasstime(this.parseInt(elem.select("div.classtimepers").first().attr("class")));
		item.setClanname(elem.select("div.clanname").first().text());
	
		return item;
	}

	@Override
	public Object parseXML(JSONObject doc, int limit) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}